package com.example.mn_mvvm_demo.login;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.databinding.ViewDataBinding;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.Observer;

import com.example.lib_cache.model.User;
import com.example.lib_cache.view_model.LoginActivityViewModel;
import com.example.lib_common.base.BaseActivity;
import com.example.mn_mvvm_demo.MainActivity;
import com.example.mn_mvvm_demo.R;
import com.example.mn_mvvm_demo.databinding.ActivityLoginBinding;

/**
 * 双向绑定     指的是 xml文件与 ViewModel 对象
 * <p>
 * 单项绑定     指的是 ViewModel 被xml文件绑定
 */
public class LoginActivity extends BaseActivity {
    private static final String TAG = LoginActivity.class.getSimpleName();
    LoginActivityViewModel loginActivityViewModel;
    ActivityLoginBinding loginBinding;

    MutableLiveData<User> userMutableLiveData;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //将xml进行绑定
        loginBinding = DataBindingUtil.setContentView(
                this,
                R.layout.activity_login
        );
        loginBinding.setLifecycleOwner(this);
        //创建activity所对应的ViewModel
        loginActivityViewModel = new LoginActivityViewModel();
        loginBinding.setViewModel(loginActivityViewModel);


        userMutableLiveData = loginBinding.getViewModel().getUser();
        userMutableLiveData.observe(this, new Observer<User>() {
            @Override
            public void onChanged(User user) {
                Log.e(TAG, "User: " + user.toString());
                if (null != user && user.getU_id() != 0) {
                    //跳转到首页
                    startActivity(new Intent(LoginActivity.this, MainActivity.class));
                    LoginActivity.this.finish();
                }
            }
        });
    }

    public void updateData(View view) {

        loginActivityViewModel.loginRequest();
    }
}
